package example;


public class Task3 {
    public static void main(String[] args) {
        String str = "abcdefgabhijkcd";
        System.out.println(method(str));
    }

    /**
     * @param str 被检索字符串
     * @return 返回str中最长不重复子串的长度
     */
    public static int method(String str) {
        if (str == null || "".equals(str))
            throw new NullPointerException();
        int length = 1, start = 0, end = start + 1;
        while (end < str.length() && start + length < str.length()) {
            int temp = seekCharOfString(str.charAt(end), str, start, end);
            if (temp != -1) {
                if (length < end - start)
                    length = end - start;
                start = temp + 1;
            }
            end++;
        }
        if (length < end - start)
            length = end - start;
        return length;
    }

    /**
     * @param character 匹配字符
     * @param str       检索字符串
     * @param start     检索区域的开始索引(包含)
     * @param end       检索区域的结束索引(不包含)
     * @return 返回str中第一个匹配到character的索引，若匹配不到，则返回-1
     */
    public static int seekCharOfString(char character, String str, int start, int end) {
        if (start < 0 || end > str.length() || start >= end)
            throw new StringIndexOutOfBoundsException();
        for (int i = start; i < end; i++)
            if (str.charAt(i) == character)
                return i;
        return -1;
    }
}
